import Singleton from "../Base/Singleton";
import { instantiate, Node, Prefab,Animation } from "cc";
import { Context } from "../Context";
import { EBuff, EEnemy, EntityType, EPet, EPlayerType, ESkill, EText, ETips,  } from "../Config/Enum";
import { EnemyManager } from "../EnemyManager";
import { ResourceManager } from "./ResourceManager";
import { PicPath, PrefabPath } from "../Config/ResourceConfig";
import { BattleManager } from "../BattleManager";
import { TangmenSkill1 } from "../Skill/TangmenSkill1";
import { EItemType } from "../Item/Item";

// 辅助函数：检查值是否在枚举中（兼容 ES5）
function isInEnum<T>(value: any, enumObj: T): boolean {
    for (const key in enumObj) {
        if (enumObj[key] === value) {
            return true;
        }
    }
    return false;
}

export default class ObjectPoolManager extends Singleton {
  static get Instance() {
    return super.GetInstance<ObjectPoolManager>();
  }

  //private objectPool: Node = null;
  private map: Map<EntityType, Node[]> = new Map();



// 获取父节点
private getParentNode(type: EntityType): Node {
    // 检查是否是敌人类型
    if (isInEnum(type, EEnemy)) {
        return BattleManager.Instance.ndEnemies;
    }

    if (isInEnum(type, EPlayerType)) {
        return BattleManager.Instance.ndPlayers;
    }

    if (isInEnum(type, ESkill)) {
        return BattleManager.Instance.ndSkills;
    }

    if (isInEnum(type, EText)) {
        return BattleManager.Instance.ndTexts;
    }
    
    if (isInEnum(type, ETips)) {
        return Context.ndTips;
    }

    if (isInEnum(type, EItemType)) {
        return BattleManager.Instance.ndItems;
    }

    if (isInEnum(type, EBuff)) {
        return BattleManager.Instance.ndSkills;
    }

    if (isInEnum(type, EPet)) {
        return BattleManager.Instance.ndPets;
    }





    
    return Context.ndDefault;
}

  reset() {
    //this.objectPool = null;
    this.map.clear();
  }

  get(entity: EntityType) {

    // if (this.objectPool === null) {
    //   this.objectPool = new Node("ObjectPool");
    //   this.objectPool.setParent(this.getParentNode(objectName));
    // }

    let parentNode = this.getParentNode(entity);

    // 
    if (!this.map.has(entity)) {
      this.map.set(entity, []); // 初始化对象池 {Enemy1: [], Player1: [], Skill1: [], Text1: [], Tips1: []}
    //   const container = new Node(this.getContainerName(entity));
    //   container.setParent(this.getParentNode(entity));
    }

    let node: Node;
    const nodes = this.map.get(entity);

    if (!nodes.length) { // 如果对象池中没有可用的节点

      // console.log("资源加载ObjectPoolManager get prefab PrefabPath[entity]", PrefabPath[entity]);
      // console.log("资源加载ObjectPoolManager get prefab ResourceManager.Instance.getResourceCache().get(PrefabPath[entity])", ResourceManager.Instance.getResourceCache().get(PrefabPath[entity]));

      const prefab = ResourceManager.Instance.getResourceCache().get(PrefabPath[entity]) as Prefab;
      // console.log("资源加载ObjectPoolManager get prefab", prefab);
      node = instantiate(prefab);
      node.name = entity;
      node.setParent(parentNode);
    } else {
      node = nodes.pop();
        // 重置动画状态
        const anim = node.getComponent(Animation);
        if (anim) {
            anim.stop();
            const state = anim.getState(anim.defaultClip.name);
            if (state) {
                state.time = 0; // 重置到第一帧
                // 强制更新一帧
                anim.play();
                //anim.stop();
            }
        }
    }
    node.active = true;
    return node;
  }

  ret(node: Node) {
    //     const comp = node.getComponent(TangmenSkill1);
    // if (comp) comp.reset();
    const objectName = node.name as EntityType;

    // // 重置动画状态（关键修复）
    // const anim = node.getComponent(Animation);
    // if (anim) {
    //     anim.stop(); // 停止当前动画
    //     const state = anim.getState(anim.defaultClip.name);
    //     if (state) {
    //         state.time = 0; // 重置到第一帧
    //         state.sample(); // 立即应用第一帧状态
    //     }
    // }


    node.active = false;
    //node.removeFromParent();
    node.position.set(0, 0, 0);
    node.angle = 0;
    node.scale.set(1, 1, 1);
    if(this.map.get(objectName)){
        this.map.get(objectName).push(node);
    }

    //console.log("ObjectPoolManager ret", objectName, "to pool, map:",this.map);
  }
}
